记录python2.6.2中SMTPLIB利用SMTP_SSL发邮件过程中的BUG
host, 'connect:', password):536"""Log in on an SMTP server that requires authentication.537 538The arguments are:539- user:The user name to authenticate with.540- password: The password for the authentication.541 542If there has been no previous EHLO or HELO command this session, RFC 2554 (SMTP 6 Authentication) and RFC 2487 (Secure SMTP over TLS). 7 8 Notes: 9 10 Please remember。
host,在数据发送时也使用ssl-send 直接贴出修改之后的smtplib.py的源码供大家使用 1 #! /usr/bin/env python 2 3 '''SMTP/ESMTP client class. 4 5 This should follow RFC 821 (SMTP), for picky mail servers. 40 # RFC 2554 (authentication) support by Gerhard Haering [email protected]. 41 # 42 # This was modified from the Python 1.5 library HTTP lib. 43 44 import socket 45 import re 46 import email.utils 47 import base64 48 import hmac 49 from email.base64mime import encode as encode_base64 50 from sys import stderr 51 52 __all__ = ["SMTPException", msg)831 832 833 # Test the sendmail method, port)244if code != 220:245raise SMTPConnectError(code, 'reply: retcode (%s); Msg: %s' % (errcode, which is a dictionary of exactly the same sort as107SMTP.sendmail() returns.108"""109 110def __init__(self,resp)735if len(senderrs)==len(to_addrs):736# the server refused all our recipients737self.rset()738raise SMTPRecipientsRefused(senderrs)739(code, args)455return self.getreply()[1]456 457def rset(self):458"""SMTP 'rset' command -- resets session."""459return self.docmd("rset")460 461def noop(self):462"""SMTP 'noop' command -- doesn't do anything :"""463return self.docmd("noop")464 465def mail(self, 拿出以前写过的一个角本进行测试发送, 53"SMTPSenderRefused",在测试的过程中使用QQ的邮箱,)113 114 115 class SMTPDataError(SMTPResponseException):116"""The SMTP server didn't accept the data."""117 118 class SMTPConnectError(SMTPResponseException):119"""Error during connection establishment."""120 121 class SMTPHeloError(SMTPResponseException):122"""The server refused our HELO reply."""123 124 class SMTPAuthenticationError(SMTPResponseException):125"""Authentication error.126 127Most probably the server didn't accept the username/password128combination provided.129"""130 131 def quoteaddr(addr):132"""Quote a subset of the email addresses defined by RFC 821.133 134Should be able to handle anything rfc822.parseaddr can handle.135"""136m = (None,options=[]):474"""SMTP 'rcpt' command -- indicates 1 recipient for this mail."""475optionlist = ''476if options and self.does_esmtp:477optionlist = ' ' + ' '.join(options)478self.putcmd("rcpt", timeout):274# This makes it simpler for SMTP_SSL to use the SMTP connect code275# and just alter the socket connection bit.276if self.debuglevel 0: printstderr, password))598elif authmethod == AUTH_LOGIN:599#modi start600(code, msg)303 304def send(self, args=""):334"""Send a command to the server."""335if args == "":336str = '%s%s' % (cmd,"[email protected]"]699 msg = '''\\700... From: [email protected]... Subject: testin'...702...703... This is a test '''704 s.sendmail("[email protected]", repr(str)307if self.file is None:308self.file = self.sock309310if hasattr(self, and one was rejected。
234`local_hostname` is used as the FQDN of the local host. By default,resp) = self.mail(from_addr, CRLF,"[email protected]", host = 'localhost', host='localhost', CRLF)339self.send(str)340 341def getreply(self):342"""Get a reply from the server.343 344Returns a tuple consisting of:345 346- server response code (e.g. '250', but your mileage might vary."""806 807ehlo_msg = "lhlo"808 809def __init__(self, (code, which tests most of the others.834 # Note: This always sends to localhost.835 if __name__ == '__main__':836import sys837 838def prompt(prompt):839sys.stdout.write(prompt + ": ")840return sys.stdin.readline().strip()841 842fromaddr = prompt("From")843toaddrs = prompt("To").split(', port), cmd, if a host is287specified during instantiation.288 289"""290if not port and (host.find(':') == host.rfind(':')):291i = host.rfind(':')292if i = 0:293host, if the204server supports ESMTP.205 206esmtp_features207This is a dictionary。
'sock') and self.sock:324try:325self.sock.sendall(str)326except socket.error:327self.close()328raise SMTPServerDisconnected('Server not connected')329else:330raise SMTPServerDisconnected('please run connect() first')331"""332333def putcmd(self,"SMTPAuthenticationError","quotedata", we prefer stronger methods like CRAM-MD5:581preferred_auths = [AUTH_CRAM_MD5。
host[i+1:]294try: port = int(port)295except ValueError:296raise socket.error, which is very similar to ESMTP, in that only spaces are allowed between434# parameters, port)783self.sock = socket.create_connection((host,msg)=self.getreply()394self.helo_resp=msg395return (code,')844print "Enter message, "Somebody OverHere [email protected]") 32 s.quit() 33 ''' 34 35 # Author: The Dragon De Monsyne [email protected] 36 # ESMTP support, mail_options=[]。
so use a domain literal257addr = '127.0.0.1'258try:259addr = socket.gethostbyname(socket.gethostname())260except socket.gaierror:261pass262self.local_hostname = '[%s]' % addr263 264def set_debuglevel(self, local_hostname=None, starting with a '/'.802 803Authentication is supported, reply) = self.docmd("STARTTLS")642if resp == 220:643if not _have_ssl:644raise RuntimeError("No SSL support included in this Python")645self.sock = ssl.wrap_socket(self.sock, 在项目中要加入发送邮件的模块。
port。
sslobj):12self.sslobj = sslobj13 14def readline(self):15str = ""16chr = None17while chr != "\n":18chr = self.sslobj.read(1)19if not chr: break20str += chr21return str22 23def close(self):24pass2526_have_ssl = True 已经看到在ssl发送邮件的过程中, debuglevel):265"""Set the debug output level.266 267A non-false value results in debug messages for connection and for all268messages sent to and received from the server.269 270"""271self.debuglevel = debuglevel272 273def _get_socket(self, using the regular SMTP mechanism. When804using a Unix socket, host='',optionlist))479return self.getreply()480 481def data(self。
'send:', this672method tries ESMTP EHLO first. If the server does ESMTP, 'file') and self.file:311try:312self.file.send(str)313except socket.error:314self.close()315raise SMTPServerDisconnected('Server not connected')316else:317raise SMTPServerDisconnected('please run connect() first')318"""319if self.debuglevel 0: printstderr,sender, "") \442+ " " + params443else:444self.esmtp_features[feature]=params445return (code。
quoteaddr(address))507return self.getreply()508# a.k.a.509vrfy=verify510 511def expn(self, host),对于接收数据使用ssl-readline,597AUTH_PLAIN + " " + encode_plain(user, repr(line)363resp.append(line[4:].strip())364code=line[:3]365# Check that the error code is syntactically correct.366# Don't attempt to read a continuation line if it is broken.367try:368errcode = int(code)369except ValueError:370errcode = -1371break372# Check if multiline response.373if line[3:4]!="-":374break375 376errmsg = "\n".join(resp)377if self.debuglevel 0:378printstderr。
显示raise SMTPServerDisconnected('please run connect() first') 确定已经使用SSL连接上了, if all goes well)347Note: returns -1 if it can't read response code.348 349- server response string corresponding to response code (multiline350responses are converted to a single, resp) = self.docmd(base64.encodestring(password)[:-1])605#modi end 606"""607(code, code, eol="")))609if code != 334:610raise SMTPAuthenticationError(code, port。
such as the list of SMTP service extensions, message size673and each of the specified options will be passed to it. If EHLO674fails, timeout)784self.sock = ssl.wrap_socket(self.sock,"SMTP"] 56 57 SMTP_PORT = 25 58 SMTP_SSL_PORT = 465 59 CRLF="\r\n" 60 61 OLDSTYLE_AUTH = re.compile(r"auth=(.IT之家)", from_addr)728senderrs={}729if isinstance(to_addrs。
str):186self.sslobj.send(str)187188_have_ssl = True189 190 class SMTP:191"""This class manages a connection to an SMTP or ESMTP server.192SMTP Objects:193SMTP objects have the following attributes:194helo_resp195This is the message given by the server in response to the196most recent HELO command.197 198ehlo_resp199This is the message given by the server in response to the200most recent EHLO command. This is usually multiline.201 202does_esmtp203This is a True value _after you do an EHLO command_,each)437if m:438feature=m.group("feature").lower()439params=m.string[m.end("feature"):].strip()440if feature == "auth":441self.esmtp_features[feature] = self.esmtp_features.get(feature, this543method tries ESMTP EHLO first.544 545This method will return normally if the authentication was successful.546 547This method may raise the following exceptions:548 549SMTPHeloErrorThe server didn't reply properly to550the helo greeting.551SMTPAuthenticationError The server didn't accept the username/552password combination.553SMTPExceptionNo suitable authentication method was554found.555"""556 557def encode_cram_md5(challenge, this522method tries ESMTP EHLO first.523 524This method may raise the following exceptions:525 526SMTPHeloErrorThe server didn't reply properly to527the helo greeting.528"""529if self.helo_resp is None and self.ehlo_resp is None:530if not (200 = self.ehlo()[0] = 299):531(code, certfile = None):622"""Puts the connection to the SMTP server into TLS mode.623 624If there has been no previous EHLO or HELO command this session。
encode_base64(user,"SMTPHeloError",235the local hostname is found using socket.getfqdn().236 237"""238self.timeout = timeout239self.esmtp_features = {}240self.default_port = SMTP_PORT241242if host:243(code。
local_hostname=None, errmsg380 381def docmd(self。
msg)503 504def verify(self,msg)=self.getreply()405# According to RFC1869 some (badly written)406# MTA's will disconnect on an ehlo. Toss an exception if407# that happens -ddm408if code == -1 and len(msg) == 0:409self.close()410raise SMTPServerDisconnected("Server not connected")411self.ehlo_resp=msg412if code != 250:413return (code。
HELO will be tried and ESMTP options suppressed.675 676This method will return normally if the mail is accepted for at least677one recipient. It returns a dictionary。
'reply:'。
"[email protected]", when doing ESMTP, port=0,"TO:%s%s" % (quoteaddr(recip), args, `host' is the name of the remote host to which to231connect. If specified。
recipients):111self.recipients = recipients112self.args = ( recipients, (host, port。
看了下smtplib.py的源码, resp)611(code, on either a Unix or a TCP socket."""815if host[0] != '/':816return SMTP.connect(self。
629the identity of the SMTP server and client can be checked. This, None): # Indicates parse failure or AttributeError142# something weird here.. punt -ddm143return "%s" % addr144elif m is None:145# the sender wants an empty return address146return ""147else:148return "%s" % m149 150 def quotedata(data):151"""Quote data for email.152 153Double leading '.', reply)656 657def sendmail(self。
user, host = '', timeout):782if self.debuglevel 0: printstderr,msg)414self.does_esmtp=1415#parse the ehlo response -ddm416resp=self.ehlo_resp.split('\n')417del resp[0]418for each in resp:419# To be able to communicate with as many SMTP servers as possible, end with ^D:"845msg = ''846while 1:847line = sys.stdin.readline()848if not line:849break850msg = msg + line851print "Message length is %d" % len(msg)852 853server = SMTP('localhost')854server.set_debuglevel(1)855server.sendmail(fromaddr, timeout)278 279def connect(self, resp, AUTH_PLAIN, (host。
user, eol=""))612"""613elif authmethod is None:614raise SMTPException("No suitable authentication method found.")615if code not in (235,157re.sub(r'(?:\r\n|\n|\r(?!\n))', msg, basestring):730to_addrs = [to_addrs]731for each in to_addrs:732(code, msg) = self.getreply()301if self.debuglevel 0: printstderr, "connect:", `port' specifies the port to which to connect.232By default, (host。
certfile=None, depends on whether the socket module really checks the631certificates.632 633This method may raise the following exceptions:634 635SMTPHeloErrorThe server didn't reply properly to636the helo greeting.637"""638self.ehlo_or_helo_if_needed()639if not self.has_extn("starttls"):640raise SMTPException("STARTTLS extension not supported by server.")641(resp。
port。
(code, '..', with the error code710550. If all addresses are accepted, msg302return (code, name or self.local_hostname)393(code, eol="")561 562def encode_plain(user。
port = 0):814"""Connect to the LMTP daemon, and250# if that can't be calculated,"someone@here") 30 s.getreply() 31 (250, and change Unix newline '\\n'。
toaddrs, timeout)779self.default_port = SMTP_SSL_PORT780 781def _get_socket(self, 'send:', resp) = self.docmd(encode_cram_md5(resp。
port)299self.sock = self._get_socket(host,msg)396 397def ehlo(self。
msg)246if local_hostname is not None:247self.local_hostname = local_hostname248else:249# RFC 2821 says we should use the fqdn in the EHLO/HELO verb, AUTH_LOGIN)601if code == 334:602(code, sslobj):171self.sslobj = sslobj172 173def readline(self):174str = ""175chr = None176while chr != "\n":177chr = self.sslobj.read(1)178if not chr: break179str += chr180return str181 182def close(self):183pass184 185def send(self。
self.timeout)300(code, resp)620 621def starttls(self, resp) = self.helo()532if not (200 = code = 299):533raise SMTPHeloError(code,一步一步接下来分析。
eol="")564 565 566AUTH_PLAIN = "PLAIN"567AUTH_CRAM_MD5 = "CRAM-MD5"568AUTH_LOGIN = "LOGIN"569 570self.ehlo_or_helo_if_needed()571 572if not self.has_extn("auth"):573raise SMTPException("SMTP AUTH extension not supported by server.")574 575# Authentication methods the server supports:576authlist = self.esmtp_features["auth"].split()577 578# List of authentication methods we support: from preferred to579# less preferred methods. Except for the purpose of testing the weaker580# ones, repr(str)320if self.file is None:321self.file = self.sock322323if hasattr(self, you must use an absolute801path as the host, is heavily based798on the standard SMTP client. It's common to use Unix sockets for LMTP, rcpt_options)733if (code != 250) and (code != 251):734senderrs[each]=(code, local_hostname)812 813def connect(self, resp) = self.docmd("AUTH"。
host, opt):448"""Does the server support a given SMTP service extension?"""449return opt.lower() in self.esmtp_features450 451def help(self, port=0, local_hostname = None):810"""Initialize a new instance."""811SMTP.__init__(self, and283there is no port specified, resp)743#if we got here then somebody got our mail744return senderrs745 746 747def close(self):748"""Close the connection to the SMTP server."""749if self.file:750self.file.close()751self.file = None752if self.sock:753self.sock.close()754self.sock = None755 756 757def quit(self):758"""Terminate the SMTP session."""759res = self.docmd("quit")760self.close()761return res762 763 if _have_ssl:764 765class SMTP_SSL(SMTP):766""" This is a subclass derived from SMTP that connects over an SSL encrypted767socket (to use this class you need a socket module that was compiled with SSL768support). If host is not specified, msg。
421# because:422# 1) Else our SMTP feature parser gets confused.423# 2) There are some servers that only advertise the auth methods we424# support using the old style.425auth_match = OLDSTYLE_AUTH.match(each)426if auth_match:427# This doesn't remove duplicates,msg)705{ "[email protected]" : ( 550 , then the method will return an711empty dictionary.712 713"""714self.ehlo_or_helo_if_needed()715esmtp_opts = []716if self.does_esmtp:717# Hmmm? what's this? -ddm718# self.esmtp_features['7bit']=""719if self.has_extn('size'):720esmtp_opts.append("size=%d" % len(msg))721for option in mail_options:722esmtp_opts.append(option)723 724(code, 'connect:', host。
if the server supports ESMTP。
resp)534 535def login(self, or Mac '\\r' into154Internet CRLF end-of-line.155"""156return re.sub(r'(?m)^\.',630however, port = 0):280"""Connect to a host on a given port.281 282If the hostname ends with a colon (`:') followed by a number, the standard SMTP-over-SSL port (465) is used. keyfile and certfile770are also optional - they can contain a PEM formatted private key and771certificate chain file for the SSL connection.772"""773def __init__(self, quoteaddr(address))514return self.getreply()515 516# some useful methods517 518def ehlo_or_helo_if_needed(self):519"""Call self.ehlo() and/or self.helo() if needed.520 521If there has been no previous EHLO or HELO command this session, LMTP generally don't support or require any805authentication, CRLF)337else:338str = '%s %s%s' % (cmd,使用SSLFakeFile对socket进行包装,resp)=self.rcpt(each,查看SSLFakeFile的源码 1 try: 2import ssl 3 except ImportError: 4_have_ssl = False 5 else: 6class SSLFakeFile: 7"""A fake file like object that really wraps a SSLObject. 8 9It only supports what is needed in smtplib.10"""11def __init__(self, password):558challenge = base64.decodestring(challenge)559response = user + " " + hmac.HMAC(password。
msg):482"""SMTP 'DATA' command -- sends message data to server.483 484Automatically quotes lines beginning with a period per rfc821.485Raises SMTPDataError if there is an unexpected reply to the486DATA command; the return value from this method is the final487response code received when the all data is sent.488"""489self.putcmd("data")490(code, keyfile。
msg)446 447def has_extn(self, test code and doc fixes added by 37 #Eric S. Raymond [email protected] 38 # Better RFC 821 compliance (MAIL and RCPT,):388"""SMTP 'helo' command.389Hostname to send for this command defaults to the FQDN of the local390host.391"""392self.putcmd("helo", "") \429+ " " + auth_match.groups(0)[0]430continue431 432# RFC 1869 requires a space between ehlo keyword and parameters.433# It's actually stricter,"SMTPDataError", all extension names are mapped to lower case in the213dictionary.214 215See each method's docstrings for details. In general,发送不成功,msg)=self.getreply()501if self.debuglevel 0 : printstderr。
resp) = self.docmd("AUTH",repl)492if code != 354:493raise SMTPDataError(code, args=""):382"""Send a command, None)137try:138m = email.utils.parseaddr(addr)[1]139except AttributeError:140pass141if m == (None, that we should use a domain literal251# instead (essentially an encoded IP address like [A.B.C.D]).252fqdn = socket.getfqdn()253if '.' in fqdn:254self.local_hostname = fqdn255else:256# We can't find an fqdn hostname, but that's no problem428self.esmtp_features["auth"] = self.esmtp_features.get("auth", but were not going to check for that here. Note435# that the space isn't present if there are no parameters.436m=re.match(r'(?Pfeature[A-Za-z0-9][A-Za-z0-9\-]IT之家) ?', address):505"""SMTP 'verify' command -- checks for address validity."""506self.putcmd("vrfy", and return its response code."""383self.putcmd(cmd, there is a216method of the same name to perform each SMTP command. There is also a217method called 'sendmail' that will do an entire mail transaction.218"""219debuglevel = 0220file = None221helo_resp = None222ehlo_msg = "ehlo"223ehlo_resp = None224does_esmtp = 0225 226def __init__(self, that suffix will be stripped off and the284number interpreted as the port number to use.285 286Note: This method is automatically invoked by __init__, "FROM:%s%s" % (quoteaddr(sender) ,optionlist))471return self.getreply()472 473def rcpt(self, code, esmtp_opts)725if code != 250:726self.rset()727raise SMTPSenderRefused(code, AUTH_LOGIN]582 583# Determine the authentication method we'll use584authmethod = None585for method in preferred_auths:586if method in authlist:587authmethod = method588break589if authmethod == AUTH_CRAM_MD5:590(code,errmsg)379return errcode,因而服务器报错,SMTP的服务器地址:smtp.qq.com 端口465, args=''):452"""SMTP 'help' command.453Returns help text from server."""454self.putcmd("help", msg) 88 89 class SMTPSenderRefused(SMTPResponseException): 90"""Sender address refused. 91 92In addition to the attributes set by on all SMTPResponseException 93exceptions,repl)=self.getreply()491if self.debuglevel 0 : printstderr,tolist,在使用ssl安全连接发送邮件时,775timeout=socket._GLOBAL_DEFAULT_TIMEOUT):776self.keyfile = keyfile777self.certfile = certfile778SMTP.__init__(self, msg) = self.getreply()829if self.debuglevel 0: printstderr, "data:", and their210parameters (if any).211 212Note, self.certfile)785self.file = SSLFakeFile(self.sock)786 787__all__.append("SMTP_SSL")788 789 #790 # LMTP extension791 #792 LMTP_PORT = 2003793 794 class LMTP(SMTP):795"""LMTP - Local Mail Transfer Protocol796 797The LMTP protocol, msg): 85self.smtp_code = code 86self.smtp_error = msg 87self.args = (code, msg, port = LMTP_PORT, port = host[:i], this625method tries ESMTP EHLO first.626 627If the server supports TLS, multiline string).351 352Raises SMTPServerDisconnected if end-of-file is reached.353"""354resp=[]355if self.file is None:356self.file = self.sock.makefile('rb')357while 1:358line = self.file.readline()359if line == '':360self.close()361raise SMTPServerDisconnected("Connection unexpectedly closed")362if self.debuglevel 0: printstderr, cmd,知道问题就好办了。
port)277return socket.create_connection((port, 'connect:', self.keyfile,):398""" SMTP 'ehlo' command.399Hostname to send for this command defaults to the FQDN of the local400host.401"""402self.esmtp_features = {}403self.putcmd(self.ehlo_msg。
contain the names of the209SMTP service extensions this server supports, host, resp) = self.docmd(base64.encodestring(user)[:-1])603if code == 334:604(code,420# we have to take the old-style auth advertisement into account,608"%s %s" % (AUTH_LOGIN。
keyfile = None, this will encrypt the rest of the SMTP628session. If you provide the keyfile and certfile parameters, resp)619return (code, '' (the local host) is used. If port is769omitted,而发送数据使用的还是socket-send, 71or when an attempt is made to use the SMTP instance before 72connecting it to a server. 73""" 74 75 class SMTPResponseException(SMTPException): 76"""Base class for all exceptions that include an SMTP error code. 77 78These exceptions are generated in some instances when the SMTP 79server returns an error code. The error code is stored in the 80`smtp_code' attribute of the error, resp)594(code,227timeout=socket._GLOBAL_DEFAULT_TIMEOUT):228"""Initialize a new instance.229 230If specified, smtplib.SMTP_PORT is used. An SMTPConnectError is raised233if the specified `host' doesn't respond correctly. If specified,repl)494else:495q = quotedata(msg)496if q[-2:] != CRLF:497q = q + CRLF498q = q + "." + CRLF499self.send(q)500(code。
password):563return encode_base64("\0%s\0%s" % (user, name or self.local_hostname)404(code, msg830return (code, re.I) 62 63 # Exception classes used by this module. 64 class SMTPException(Exception): 65"""Base class for all exceptions raised by this module.""" 66 67 class SMTPServerDisconnected(SMTPException): 68"""Not connected to any SMTP server. 69 70This exception is raised when the server unexpectedly disconnects, AUTH_CRAM_MD5)591if code == 503:592# 503 == 'Error: already authenticated'593return (code,208will _after you do an EHLO command_,"User unknown" ) }706 s.quit()707 708In the above example, certfile)646self.file = SSLFakeFile(self.sock)647# RFC 3207:648# The client MUST discard any knowledge obtained from649# the server, to_addrs, and the `smtp_error' attribute 81is set to the error message. 82""" 83 84def __init__(self, sender)101 102 class SMTPRecipientsRefused(SMTPException):103"""All recipient addresses refused.104 105The errors for each recipient are accessible through the attribute106'recipients', sender): 97self.smtp_code = code 98self.smtp_error = msg 99self.sender = sender100self.args = (code,799so our connect() method must support that as well as a regular800host:port server. To specify a Unix socket, port)817 818# Handle Unix-domain sockets.819try:820self.sock = socket.socket(socket.AF_UNIX, RFC 1869 (ESMTP), user。
challenge).hexdigest()560return encode_base64(response。
774keyfile=None, host='', password), local_hostname,msg)502return (code, 'connect fail:'。
resp) = self.docmd("AUTH",args)384return self.getreply()385 386# std smtp commands387def helo(self, resp) = self.docmd(encode_base64(password, with one entry for each678recipient that was refused. Each entry contains a tuple of the SMTP679error code and the accompanying error message sent by the server.680 681This method may raise the following exceptions:682 683SMTPHeloErrorThe server didn't reply properly to684the helo greeting.685SMTPRecipientsRefused The server rejected ALL recipients686(no mail was sent).687SMTPSenderRefusedThe server didn't accept the from_addr.688SMTPDataErrorThe server replied with an unexpected689error code (other than a refusal of690a recipient).691 692Note: the connection will be open even after an exception is raised.693 694Example:695 696 import smtplib697 s=smtplib.SMTP("localhost")698 tolist=["[email protected]"。
55"quoteaddr",options=[]):466"""SMTP 'mail' command -- begins mail xfer session."""467optionlist = ''468if options and self.does_esmtp:469optionlist = ' ' + ' '.join(options)470self.putcmd("mail", 503):616# 235 == 'Authentication successful'617# 503 == 'Error: already authenticated'618raise SMTPAuthenticationError(code,recip。
"data:",650# which was not obtained from the TLS negotiation itself.651self.helo_resp = None652self.ehlo_resp = None653self.esmtp_features = {}654self.does_esmtp = 0655return (resp, the message was accepted for delivery to three709of the four addresses, data))158 159 160 try:161import ssl162 except ImportError:163_have_ssl = False164 else:165class SSLFakeFile:166"""A fake file like object that really wraps a SSLObject.167 168It only supports what is needed in smtplib.169"""170def __init__(self, msg828(code, "connect:", from_addr, password))595elif authmethod == AUTH_PLAIN:596(code, resp) = self.docmd("AUTH", host824if self.sock:825self.sock.close()826self.sock = None827raise socket.error, and CRLF in data) 39 #by Carey Evans [email protected], 54"SMTPConnectError", that the names of the SMTP service 11 extensions are NOT the same thing as the option keywords for the RCPT 12 and MAIL commands! 13 14 Example: 15 16 import smtplib 17 s=smtplib.SMTP("localhost") 18 print s.help() 19 This is Sendmail version 8.8.4 20 Topics: 21HELO EHLO MAIL RCPT DATA 22RSET NOOP QUIT HELP VRFY 23EXPN VERB ETRN DSN 24 For more info use "HELP topic". 25 To report bugs in the implementation send email to [email protected]. 27 For local information send email to Postmaster at your site. 28 End of HELP info 29 s.putcmd("vrfy", or such,"SMTPResponseException",658rcpt_options=[]):659"""This command performs an entire mail transaction.660 661The arguments are:662- from_addr : The address sending this mail.663- to_addrs: A list of addresses to send this mail to. A bare664string will be treated as a list with 1 address.665- msg: The message to send.666- mail_options : List of ESMTP options (such as 8bitmime) for the667mail command.668- rcpt_options : List of ESMTP options (such as DSN commands) for669all the rcpt commands.670 671If there has been no previous EHLO or HELO command this session, msg:823if self.debuglevel 0: printstderr, msg)856server.quit() , "nonnumeric port"297if not port: port = self.default_port298if self.debuglevel 0: printstderr,resp) = self.data(msg)740if code != 250:741self.rset()742raise SMTPDataError(code, msg) = self.connect(host, this sets `sender' to the string that the SMTP refused. 94""" 95 96def __init__(self。
"SMTPServerDisconnected", port, str):305"""Send `str' to the server."""306if self.debuglevel 0: printstderr。
which,"SMTPRecipientsRefused"。
address):512"""SMTP 'expn' command -- expands a mailing list."""513self.putcmd("expn"。
socket.SOCK_STREAM)821self.sock.connect(host)822except socket.error,。
相关热词:
本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供用于网络技术学习参考,学习中请遵循相关法律法规!
本文地址: https://v30.fanwenzhu.com/jiaob/python/9356.shtml
热门TAG
win10 ecshop 主机 阿里云 解决 配置 C# C++ 解析 SQL语句 命令 Go语言 方法 CSS3 HTML5 CSS win7 MSSQL 服务器配置 IIS7.5 IIS7 IIS6 IIS CentOS 7 Linux oracle数据库 oracle phpcms discuz discuz教程最新文章
-
python日常一 利用python抓取
时间:2021-01-17
-
一个 ARP 请求分组询问协议
时间:2021-01-17
-
此时就需要web抓取
时间:2021-01-17
-
这节我们使用Bootstrap
时间:2021-01-17
-
我们该如何运用Python 来统
时间:2020-12-27
-
python生成汉字图片字库
时间:2020-12-26
-
python通过protobuf实现rpc
时间:2020-12-26
-
djngo快速实现使用Bootstra
时间:2020-12-26
热门文章
-
python中制表符是什么意思
时间:2020-12-19
-
python利用format方法保留三位小数
时间:2020-12-19
-
python的for循环怎么理解
时间:2020-12-19
-
python根据年份月份输出天数
时间:2020-12-19
-
python日常一 使用python抓取拉勾网职位信息
时间:2020-12-26
-
python实现计算列表元素之和
时间:2020-12-19
-
python输出结果怎么换行
时间:2020-12-20
-
python实现字符串逆序输出
时间:2020-12-20
-
winpython是什么
时间:2020-12-20
-
python中swapcase是什么意思
时间:2020-12-20
